package com.situ.shoplook.admin.api;

import com.situ.shoplook.admin.model.User;
import com.situ.shoplook.admin.service.UserService;
import com.situ.shoplook.admin.util.CaptchaUtils;
import com.situ.shoplook.common.model.Account;
import com.situ.shoplook.common.util.JwtUtils;
import com.situ.shoplook.common.util.WebAppContext;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * 功能：后台管理员
 *
 * @author 千堆雪
 * @version 1.0.0
 * <p>
 * created by 千堆雪 on 2024/8/24, last modified by 千堆雪 on 2024/8/24
 */
@RestController
@RequestMapping(value = "/api/v1/users", produces = "application/json;charset=utf-8")
public class UserApi {
    private static final PasswordEncryptor PASSWORD_ENCRYPTOR = new StrongPasswordEncryptor();
    private UserService userService;

    //jwt加密解密用的key
    @Value("${jwt.secret.key}")
    private String secretKey;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 响应状态码图片
     *
     * @param resp 响应状态码图片
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        CaptchaUtils.out(specCaptcha, req, resp);
    }

    /**
     * 提交登录
     *
     * @return 登录数据
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Account account, HttpSession session) {
        if (!StringUtils.hasText(account.getCaptcha())) {
            return Map.of("success", false, "error", "验证码不可为空");
        }

        String captcha = (String) session.getAttribute("captcha");
        if (!account.getCaptcha().equals(captcha)) {
            return Map.of("success", false, "error", "验证码不正确");
        }

        if (!StringUtils.hasText(account.getUsername())) {
            return Map.of("success", false, "error", "用户名不可为空");
        }

        if (!StringUtils.hasText(account.getPassword())) {
            return Map.of("success", false, "error", "密码不可为空");
        }

        User user = userService.findByUsername(account.getUsername());
        if (user == null) {
            return Map.of("success", false, "error", "无此用户");
        }

        boolean passed = PASSWORD_ENCRYPTOR.checkPassword(account.getPassword(), user.getPassword());

        if (passed) {
            //创建jwt
            String jwt = JwtUtils.encode(account, 30, secretKey);

            //当使用session机制认证的时候，需要将用户信息存储到session中，而当使用jwt机制认证的时候，此操作就无意义了。
            session.setAttribute("current_login_account", account);

            //设置到本地线程
            WebAppContext.setCurrentAccount(account);

            return Map.of("success", true, "user", user, "jwt", jwt);
        } else {
            return Map.of("success", false, "error", "密码不正确");
        }
    }
}
